# -*- coding: utf-8 -*-
from abc import ABC

from app.models import db_session
from app.views import CommonHandler
from app.models.dao import add, delete, db2vectors
from app.models.model import TrackModel
from app.tools.utils import distance, THRESHOLD


def get_tracks(meta_id, type):
    session = db_session()
    features = session.query(TrackModel).filter(
        TrackModel.meta_id == meta_id,
        TrackModel.dxftype == type
    ).all()
    session.close()
    tracks = [feature.vector() for feature in features]

    for track in tracks:
        points = [track["points"][0]]
        for i in range(1, len(track["points"])):
            last = len(points) - 1
            x1, y1 = points[last][0], points[last][1]
            x2, y2 = track["points"][i][0], track["points"][i][1]
            if distance(x1, y1, x2, y2) < THRESHOLD:
                continue
            points.append([x2, y2])
        track["points"] = points
    return tracks


# person_tracks = get_tracks("person", "person")
# vehicle_tracks = get_tracks("vehicle", "vehicle")


class TrackHandler(CommonHandler, ABC):
    async def get(self):
        meta_id = self.get_argument("meta_id", None)
        dxftype = self.get_argument("type", None)
        tracks = get_tracks(meta_id, dxftype)
        await self.response(data=tracks)

    async def post(self):
        params = self.json_params()
        track = TrackModel(params['points'], params['meta_id'])
        track.dxftype = params['type']
        add(track)
        tracks = db2vectors(TrackModel, params['meta_id'])
        await self.response(data=tracks)

    async def delete(self):
        params = self.json_params()
        delete(TrackModel, params['id'])
        tracks = db2vectors(TrackModel, params['meta_id'])
        await self.response(data=tracks)


if __name__ == '__main__':
    pass